<template>
	<view class="content" style="background-color: #F4F4F4;height: 100vh;">
		<tn-nav-bar bgClass="bg-gradual-blue">
			<view>
				{{ bleName }}
			</view>
		</tn-nav-bar>
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class="margin-sm">
				<view class="margin-tb-sm">
					<tn-list-cell hover radius @click="showKeyboard('PACK_FCC')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">电池包设计容量</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['PACK_FCC']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> AH</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover radius @click="showKeyboard('TOV')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">总压过压保护电压</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['TOV']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> V</text>
							</view>
						</view>
					</tn-list-cell>
				</view>

				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('TOVR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">总压过压保护释放电压</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['TOVR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> V</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTD')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">高温放电保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTD']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTDR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">高温放电保护释放温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTDR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTC')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">高温充电保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTC']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTCR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">高温充电保护释放温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTCR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTD')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">低温放电保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTD']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTDR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">低温放电保护释放温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTDR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTC')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">低温充电保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTC']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTCR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">低温充电保护释放温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTCR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OCD')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">放电过流保护值</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OCD']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OCDR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">放电过流保护释放值</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OCDR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OCC')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">充电过流保护值</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OCC']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> A</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OCCR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">充电过流保护释放值</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OCCR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> A</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
			</view>


			<view style="height: 10vh;"></view>
			<tn-modal :value="showKey" @click="setBleVal" @cancel="onDialogClose" custom :button="buttons"
				padding='30rpx'>
				<view class="custom-modal-content">
					<tn-form :labelWidth="140" style="width: 100%;">
						<tn-form-item :borderBottom="false">
							<tn-input v-model="inputValue" border type="number"></tn-input>
						</tn-form-item>
					</tn-form>
				</view>
			</tn-modal>
		</view>
	</view>
</template>

<script>
	import BLE from "@/libs/bluetooth/BLE.js";
	import Protocol from "@/libs/protocol/anxuan/protocol.js";
	import bleData from "@/libs/protocol/anxuan/bleData.js";

	let timer = null;
	let sendTimer = null;
	export default {
		data() {
			return {
				bleName: '',
				inputValue: '',
				showKey: false,
				isFirst: true,
				isWrite: false,
				readIndex: 0,
				activeItem: null,
				buttons: [{
						text: '取消',
						backgroundColor: '#AAAAAA',
						fontColor: '#FFFFFF'
					},
					{
						text: '确定',
						backgroundColor: '#01BEFF',
						fontColor: '#FFFFFF'
					}
				],
				readList: bleData.writeList,
				writeValue: bleData.writeValue,
				readAllParams: bleData.readAndWrite,
				readValue: {},
				resData: '',
				lenValue: 0,
				nValue: 0,
				xValue: 0,
			}
		},
		onLoad(options) {
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
			if (options.n) {
				this.bleName = options.n
			}
			var that = this;
			let readValue = {}
			//设置值更改函数
			that.SetValueChanged();
			that.isWrite = false;
			that.readIndex = 0;
		},
		onShow() {
			if (!getApp().globalData.bleObj.state) {
				BLE.Connect(getApp().globalData.bleObj.deviceId, () => {})
			}
			let that = this
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			that.readAllParams.map(t => {
				that.readValue[t.name] = ''
			})
			that.isWrite = false;
			//设置值更改函数
			that.SetValueChanged();
			that.sendFirstToBle()
			//定时读取蓝牙数据
			timer = setInterval(() => {
				that.sendFirstToBle()
			}, 2000)
		},
		onHide() {
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			this.isWrite = true
		},
		beforeDestroy() {
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			this.resData = ''
			this.readIndex = 0;
		},
		methods: {
			setBleVal(e) {
				if (e.index < 1) {
					this.showKey = false
					this.inputValue = ''
					return
				}
				let that = this
				this.$tn.message.toast('下发中')
				let address = that.writeValue[that.activeItem]
				let v = parseFloat(that.inputValue);
				if (!isNaN(v)) {
					console.log('v', v);
					Protocol.writeToWrite(address, Protocol.encryption(address, v), async () => {
						console.log('发送指令成功');
						that.readValue[that.activeItem] = that.inputValue
						that.showKey = false
						that.$tn.message.toast('指令下发成功')
					})
				}
			},
			onDialogClose() {
				this.showKey = false;
			},
			showKeyboard(item) {
				this.activeItem = item;
				this.showKey = true
				this.inputValue = this.readValue[item]
			},
			sendFirstToBle() {
				let that = this
				var state = getApp().globalData.bleObj.state;
				var deviceId = getApp().globalData.bleObj.deviceId;
				var isWrite = that.isWrite;
				if (state && deviceId != '' && isWrite === false) {
					that.readIndex = 0;
					that.isWrite = true;
					Protocol.writeToRead('1000', '0007', function(res) {
						console.log('sendFirstToBle');
					});
				}
			},
			//设置蓝牙请求数据
			SetValueChanged() {
				var that = this;
				//处理数据
				BLE.bleCallBack.CharacteristicValueChange = async (res) => {
					if (res != undefined && res != null && res != '') {
						var current = that.readList[that.readIndex];
						var packages = Protocol.solutionData(res, current.len);
						if (packages) {
							if (packages.command == '03') {
								let items = await loadData(that.readAllParams, packages, current.start, that);
								console.log('that.readValue', that.readValue);
								that.readAllParams = JSON.parse(JSON.stringify(items))
								that.$forceUpdate()
								that.readIndex = that.readIndex + 1;
								if (that.readIndex >= that.readList.length) {
									that.readIndex = 0;
								}
								if (timer != null) {
									Protocol.writeToRead(that.readList[that.readIndex].start,
										'000' + that.readList[that.readIndex].len, () => {
											that.isWrite = true
										});
								}
							} else {
								that.isWrite = false
								console.log('packages', packages);
							}
						} else {
							that.isWrite = false
						}
					}
				}
			},
		}
	}

	/**
	 * 解析数据
	 * @param {Object} readData
	 * @param {Object} packages
	 * @param {Object} address
	 */
	async function loadData(items, packages, address, that) {
		var j = 0;
		var length = packages.length * 0.5;
		for (var i = 0; i < items.length; i++) {
			if (items[i].address == address) {
				j = i;
				break;
			}
		}
		for (var i = 0; i < length; i++) {
			var v = packages.data.substr((i * 4), 4);
			var t = items[(j + i)];
			var value = Protocol.algorithm(t.address, v);
			if (t.address === '1014') { //总压欠压保护电压值
				let v = getPROTECT(value)
				let MAC = getApp().globalData.bleObj.MAC
				let saveArr = await that.$util.readListWithFilterExpire(MAC + "PROTECT")
				for (var m = 0; m < v.length; m++) {
					let n = v[m]
					if (n.value > 0) {
						let it = {
							serialNumber: MAC,
							createTime: that.$util.parseTime(new Date()),
							alertName: n.name
						}
						saveArr.push(it)
						if (saveArr.length > 5) {
							saveArr.splice(0, 1)
						}
					}
				}
				that.$util.saveListWithExpire(MAC + "PROTECT", saveArr, 172800)
			}
			t.value = value;
			that.readValue[t.name] = t.value ? t.value : ''
		}
		return items;
	}


	function getPROTECT(binaryData) {
		const bitInfo = [{
				name: '短路保护',
				value: binaryData[0]
			},
			{
				name: '压差保护',
				value: binaryData[1]
			},
			{
				name: '放电二级过流',
				value: binaryData[2]
			},
			{
				name: '充电过流',
				value: binaryData[3]
			},
			{
				name: '放电过流',
				value: binaryData[4]
			},
			{
				name: '总压过压',
				value: binaryData[5]
			},
			{
				name: '总压欠压',
				value: binaryData[6]
			},
			{
				name: '单体过压',
				value: binaryData[7]
			},
			{
				name: '单体欠压',
				value: binaryData[8]
			},
			{
				name: '充电高温保护',
				value: binaryData[9]
			},
			{
				name: '充电低温保护',
				value: binaryData[10]
			},
			{
				name: '放电高温保护',
				value: binaryData[11]
			},
			{
				name: '放电低温保护',
				value: binaryData[13]
			}
		];
		return bitInfo;
	}
</script>


<style lang="scss" scoped>
	.list {
		&__left {
			display: flex;
			align-items: center;
			justify-content: flex-start;

			&__icon,
			&__image {
				margin-right: 18rpx;
			}
		}

		&__right {
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}

	.list-icon-text,
	.list-image-text {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.list-image-text {
		.list {
			&__left {
				&__image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
</style>